<template>
  <div>
    <el-input disabled :value="$route.query.roleName"></el-input>
    <el-tree
      v-loading="loading"
      class="margin"
      :data="allPermissions"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys="defKeys"
      :props="defaultProps"
      ref="tree"
    >
    </el-tree>
    <el-button type="primary" @click="saveRole">保存</el-button>
    <el-button @click="$router.replace({ name: 'Sole' })">取消</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      defKeys: [], // 默认选中的id数组
      allPermissions: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      loading: false,
    };
  },
  created() {
    this.getPermissions();
  },
  methods: {
    async getPermissions() {
      this.loading = true;
      const res = await this.$Api.permission.toAssign(this.$route.params.id);
      if (res.code == 20000) {
        this.loading = false;
        const allPermissions = res.data.children;
        this.allPermissions = allPermissions;
        this.defKeys = this.getCheckedIds(allPermissions);
      }
    },
    // 获取选中的id
    getCheckedIds(auths, initArr = []) {
      return auths.reduce((pre, item) => {
        if (item.select && item.level === 4) {
          pre.push(item.id);
        } else if (item.children) {
          this.getCheckedIds(item.children, initArr);
        }
        return pre;
      }, initArr);
    },
    async saveRole() {
      const permissionId = this.$refs.tree.getCheckedKeys().join(",");
      const res = await this.$Api.permission.doAssign(
        this.$route.params.id,
        permissionId
      );
      if ((res.code = 20000)) {
        this.$message.success("保存成功");
        this.$router.replace({ name: "Sole" });
      }
    },
  },
};
</script>

<style></style>
